package listeners;

import gui.panel.ConversationPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.MessageFormat;

import javax.swing.DefaultListModel;
import javax.swing.ListModel;

import Signals.TextMessage;

import network.NetworkInterface;

public class SendListener implements ActionListener {

	private NetworkInterface networkInterface;
	private ConversationPanel panel;
	
	public SendListener(NetworkInterface networkInterface, ConversationPanel panel) {
		this.networkInterface = networkInterface;
		this.panel = panel;
	}
	
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		DefaultListModel model = (DefaultListModel)this.panel.getListInterlocutors().getModel();
		
		String username = model.getElementAt(0).toString();
		
		// send the message
		try {
			TextMessage msgToSend = new TextMessage(this.networkInterface.getNickname(), this.panel.getTxtMessageToSend().getText());
			this.networkInterface.getSendManager().sendUnicast(msgToSend, InetAddress.getByName(this.networkInterface.parseIP(username)));
			this.panel.getTxtChatHistory().setText(this.panel.getTxtChatHistory().getText() + "\nMe: " + msgToSend.getMessage());
			this.panel.getTxtMessageToSend().setText("");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
